<template>
  <div class="post-detail-container">
    <div class="header">
      <button @click="$router.go(-1)" class="back-btn">← 返回</button>
    </div>

    <div v-if="loading" class="loading">加载中...</div>
    <div v-else-if="error" class="error">{{ error }}</div>
    <div v-else-if="post" class="post-content">
      <div class="post-header">
        <div class="user-info">
          <div class="avatar">
            <img v-if="post.userAvatar" :src="$http.defaults.baseURL + post.userAvatar" :alt="post.username" class="avatar-image">
            <span v-else>{{ post.username ? post.username.charAt(0) : '?' }}</span>
          </div>
          <div class="user-details">
            <span class="username">@{{ post.username || '未知用户' }}</span>
            <span class="timestamp">{{ formatDate(post.timestamp) }}</span>
          </div>
        </div>
      </div>

      <!-- 多张图片显示 -->
      <div class="post-images-container" v-if="post.images && post.images.length > 0">
        <div class="images-grid" :class="getDetailImageGridClass(post.images.length)">
          <img v-for="(image, index) in post.images" 
               :key="index" 
               :src="$http.defaults.baseURL.replace(/\/$/, '') + image" 
               alt="帖子图片" 
               class="detail-image-item"
               @click="openImageViewer(index)">
        </div>
      </div>
      
      <!-- 兼容旧数据 -->
      <div class="post-image-container" v-else-if="post.image">
        <img :src="$http.defaults.baseURL.replace(/\/$/, '') + post.image" alt="帖子图片" class="post-image" @click="openImageViewer(0)">
      </div>

      <div class="post-text-content">
        <h1 class="post-title">{{ post.title || '无标题' }}</h1>
        <p class="post-text">{{ post.content || '无内容' }}</p>
        
        <!-- 标签显示 -->
        <div class="post-tags" v-if="post.tags && post.tags.length > 0">
          <span v-for="(tag, index) in post.tags" :key="index" class="tag-item">
            #{{ tag }}
          </span>
        </div>
      </div>

      <div class="post-actions">
        <button class="action-btn" @click="toggleLike" :class="{ liked: isLiked }">
          <i class="icon like-icon">❤️</i>
          <span>{{ post.likes || 0 }}</span>
        </button>
        <button class="action-btn">
          <i class="icon comment-icon">💬</i>
          <span>评论</span>
        </button>
        <button class="action-btn">
          <i class="icon share-icon">↗️</i>
          <span>分享</span>
        </button>
      </div>

      <div class="comments-section">
        <h3>评论</h3>
        <div class="comment-input">
          <textarea v-model="newComment" placeholder="写下你的评论..."></textarea>
          <button @click="addComment" class="comment-btn">发布</button>
        </div>
        <div class="comments-list">
          <div v-if="comments.length === 0" class="no-comments">
            还没有评论，快来抢沙发吧！
          </div>
          <div v-else v-for="comment in comments" :key="comment.id" class="comment-item">
            <div class="comment-avatar">
              <img v-if="comment.userAvatar" :src="$http.defaults.baseURL.replace(/\/$/, '') + comment.userAvatar" :alt="comment.username" class="avatar-image">
              <span v-else>{{ comment.username.charAt(0) }}</span>
            </div>
            <div class="comment-content">
              <div class="comment-header">
                <span class="comment-username">{{ comment.username }}</span>
                <span class="comment-time">{{ formatDate(comment.timestamp) }}</span>
              </div>
              <p class="comment-text">{{ comment.content }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 图片查看器 -->
    <div v-if="showImageViewer" class="image-viewer" @click="closeImageViewer">
      <div class="viewer-content" @click.stop>
        <button class="viewer-close" @click="closeImageViewer">&times;</button>
        <button class="viewer-nav viewer-prev" @click="prevImage" v-if="currentImageIndex > 0">&lt;</button>
        <img :src="getCurrentImage()" alt="查看图片" class="viewer-image">
        <button class="viewer-nav viewer-next" @click="nextImage" v-if="currentImageIndex < getMaxImageIndex()">&gt;</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'PostDetail',
  data() {
    return {
      post: null,
      loading: true,
      error: null,
      isLiked: false,
      newComment: '',
      comments: [],
      showImageViewer: false,
      currentImageIndex: 0
    }
  },
  async created() {
    await this.loadPostDetail();
    await this.loadComments();
  },
  methods: {
    async loadPostDetail() {
      const postId = this.$route.params.id;
      if (!postId) {
        this.error = '帖子ID无效';
        this.loading = false;
        return;
      }

      try {
        const response = await this.$http.get(`/api/posts/${postId}`);
        this.post = response.data;
        this.loading = false;
      } catch (error) {
        console.error('加载帖子详情失败:', error);
        this.error = error.response?.data?.error || '加载帖子失败，请重试';
        this.loading = false;
      }
    },
    async loadComments() {
      const postId = this.$route.params.id;
      if (!postId) return;

      try {
        const response = await this.$http.get(`/api/posts/${postId}/comments`);
        this.comments = response.data;
      } catch (error) {
        console.error('加载评论失败:', error);
        // 不显示错误，静默失败
      }
    },
    formatDate(timestamp) {
      if (!timestamp) return '';
      try {
        const date = new Date(timestamp);
        const now = new Date();
        const diff = now - date;
        
        // 小于1分钟
        if (diff < 60000) {
          return '刚刚';
        }
        // 小于1小时
        if (diff < 3600000) {
          return Math.floor(diff / 60000) + '分钟前';
        }
        // 小于1天
        if (diff < 86400000) {
          return Math.floor(diff / 3600000) + '小时前';
        }
        // 小于7天
        if (diff < 604800000) {
          return Math.floor(diff / 86400000) + '天前';
        }
        
        // 超过7天显示具体日期
        return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
      } catch (e) {
        return '';
      }
    },
    async toggleLike() {
      if (!this.post) return;
      
      try {
        // 调用点赞API
        const response = await this.$http.post(`/api/posts/${this.post.id}/like`);
        
        // 更新本地点赞数
        this.post.likes = response.data.likes;
        this.isLiked = true; // 点赞后设置为已点赞状态
        
      } catch (error) {
        console.error('点赞操作失败:', error);
        if (error.response?.status === 401) {
          alert('请先登录');
          this.$router.push('/login');
        } else {
          alert('点赞失败，请重试');
        }
      }
    },
    async addComment() {
      if (!this.newComment.trim()) {
        alert('请输入评论内容');
        return;
      }

      const token = localStorage.getItem('token');
      
      if (!token) {
        alert('请先登录');
        this.$router.push('/login');
        return;
      }

      try {
        // 调用评论API
        const response = await this.$http.post(`/api/posts/${this.post.id}/comments`, {
          content: this.newComment.trim()
        });

        // 将新评论添加到列表顶部
        this.comments.unshift(response.data);
        this.newComment = '';
        
      } catch (error) {
        console.error('发布评论失败:', error);
        if (error.response?.status === 401) {
          alert('请先登录');
          this.$router.push('/login');
        } else {
          alert('发布评论失败，请重试');
        }
      }
    },
    getDetailImageGridClass(imageCount) {
      // 详情页图片布局
      if (imageCount === 1) return 'detail-grid-1';
      if (imageCount === 2) return 'detail-grid-2';
      if (imageCount === 3) return 'detail-grid-3';
      return 'detail-grid-4';
    },
    openImageViewer(index) {
      this.currentImageIndex = index;
      this.showImageViewer = true;
    },
    closeImageViewer() {
      this.showImageViewer = false;
    },
    prevImage() {
      if (this.currentImageIndex > 0) {
        this.currentImageIndex--;
      }
    },
    nextImage() {
      const maxIndex = (this.post.images || (this.post.image ? [this.post.image] : [])).length - 1;
      if (this.currentImageIndex < maxIndex) {
        this.currentImageIndex++;
      }
    },
    getCurrentImage() {
      const images = this.post.images || (this.post.image ? [this.post.image] : []);
      const imageUrl = images[this.currentImageIndex];
      // 使用baseURL拼接完整的图片地址
      if (imageUrl && !imageUrl.startsWith('http')) {
        return this.$http.defaults.baseURL + imageUrl;
      }
      return imageUrl;
    },
    getMaxImageIndex() {
      return (this.post.images || (this.post.image ? [this.post.image] : [])).length - 1;
    }
  }
}
</script>

<style scoped>
.post-detail-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background: white;
  min-height: 100vh;
}

.header {
  padding: 20px 0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 20px;
}

.back-btn {
  background: none;
  border: none;
  color: #666;
  font-size: 16px;
  cursor: pointer;
  padding: 8px 16px;
  border-radius: 20px;
  transition: background-color 0.3s;
}

.back-btn:hover {
  background-color: #f5f5f5;
}

.loading, .error {
  text-align: center;
  padding: 50px;
  font-size: 16px;
}

.error {
  color: #ff2449;
}

.post-content {
  background: white;
  border-radius: 10px;
  overflow: hidden;
}

.post-header {
  padding: 20px;
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.avatar {
  width: 40px;
  height: 40px;
  background: #ff2449;
  color: white;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: bold;
  font-size: 16px;
  overflow: hidden;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}

.user-details {
  display: flex;
  flex-direction: column;
}

.username {
  font-weight: 600;
  color: #333;
  font-size: 16px;
}

.timestamp {
  font-size: 14px;
  color: #999;
  margin-top: 2px;
}

/* 多张图片显示样式 */
.post-images-container {
  width: 100%;
  margin: 20px 0;
  border-radius: 8px;
  overflow: hidden;
}

.images-grid {
  display: grid;
  gap: 2px;
  width: 100%;
}

.detail-grid-1 {
  grid-template-columns: 1fr;
  height: 500px;
}

.detail-grid-2 {
  grid-template-columns: 1fr 1fr;
  height: 350px;
}

.detail-grid-3 {
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  height: 500px;
}

.detail-grid-3 .detail-image-item:first-child {
  grid-row: span 2;
}

.detail-grid-4 {
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  height: 400px;
}

.detail-image-item {
  width: 100%;
  height: 100%;
  object-fit: cover;
  cursor: pointer;
  transition: opacity 0.3s ease;
}

.detail-image-item:hover {
  opacity: 0.8;
}

/* 兼容旧数据 */
.post-image-container {
  width: 100%;
  margin: 20px 0;
  border-radius: 8px;
  overflow: hidden;
}

.post-image {
  width: 100%;
  height: 400px;
  object-fit: cover;
  cursor: pointer;
  transition: opacity 0.3s ease;
}

.post-image:hover {
  opacity: 0.8;
}

.post-text-content {
  padding: 20px;
}

.post-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 16px;
  line-height: 1.4;
}

.post-text {
  font-size: 16px;
  line-height: 1.6;
  color: #666;
  white-space: pre-wrap;
}

/* 标签样式 */
.post-tags {
  margin-top: 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-item {
  background: #fff5f7;
  color: #ff2449;
  padding: 4px 10px;
  border-radius: 16px;
  font-size: 14px;
  font-weight: 500;
}

.post-actions {
  display: flex;
  justify-content: space-around;
  padding: 20px;
  border-top: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
}

.action-btn {
  background: none;
  border: none;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  border-radius: 25px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
  color: #666;
}

.action-btn:hover {
  background-color: #f5f5f5;
}

.action-btn.liked {
  color: #ff2449;
  background-color: #fff0f0;
}

.icon {
  font-size: 18px;
}

.comments-section {
  padding: 20px;
}

.comments-section h3 {
  margin-bottom: 20px;
  color: #333;
  font-size: 18px;
}

.comment-input {
  margin-bottom: 20px;
}

.comment-input textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  resize: vertical;
  min-height: 80px;
  font-size: 14px;
  font-family: inherit;
}

.comment-btn {
  margin-top: 10px;
  padding: 8px 20px;
  background: #ff2449;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
}

.comment-btn:hover {
  background: #e01e3e;
}

.comments-list {
  margin-top: 20px;
}

.no-comments {
  text-align: center;
  color: #999;
  padding: 40px;
  font-size: 14px;
}

.comment-item {
  display: flex;
  gap: 12px;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.comment-avatar {
  width: 32px;
  height: 32px;
  background: #ff2449;
  color: white;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: bold;
  font-size: 14px;
  flex-shrink: 0;
  overflow: hidden;
}

.comment-avatar .avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.comment-username {
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

.comment-text {
  font-size: 14px;
  line-height: 1.5;
  color: #666;
}

/* 图片查看器样式 */
.image-viewer {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.viewer-content {
  position: relative;
  max-width: 90%;
  max-height: 90%;
}

.viewer-image {
  max-width: 100%;
  max-height: 80vh;
  object-fit: contain;
}

.viewer-close {
  position: absolute;
  top: -40px;
  right: 0;
  background: none;
  border: none;
  color: white;
  font-size: 30px;
  cursor: pointer;
  padding: 5px 10px;
}

.viewer-nav {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;
  font-size: 24px;
  padding: 15px 20px;
  cursor: pointer;
  border-radius: 50%;
  transition: background 0.3s ease;
}

.viewer-nav:hover {
  background: rgba(255, 255, 255, 0.3);
}

.viewer-prev {
  left: -60px;
}

.viewer-next {
  right: -60px;
}

@media (max-width: 768px) {
  .post-detail-container {
    padding: 10px;
  }
  
  .post-title {
    font-size: 20px;
  }
  
  .post-text {
    font-size: 15px;
  }
  
  .post-actions {
    padding: 15px 10px;
  }
  
  .action-btn {
    padding: 10px 15px;
    font-size: 13px;
  }
}
</style>